package com.wushi.lenovo.asia5b.app_ui.other.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.os.Bundle;
import android.support.annotation.IntRange;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.permissions.RxPermissions;
import com.mvp.base.BaseFragmentPagerAdapter;
import com.mvp.base.BaseMvpActivity;
import com.mvp.common.GlobalValue;
import com.mvp.event.TaokouEvent;
import com.wushi.lenovo.asia5b.BuildConfig;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_config.InboxRepository;
import com.wushi.lenovo.asia5b.app_config.MalayAsiaApplication;
import com.wushi.lenovo.asia5b.app_config.MemberBlanceRepository;
import com.wushi.lenovo.asia5b.app_config.OrderRepository;
import com.wushi.lenovo.asia5b.app_config.ShopRepository;
import com.wushi.lenovo.asia5b.app_config.UserRepository;
import com.wushi.lenovo.asia5b.app_config.WishRepository;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.other.mvpview.MainActivityView;
import com.wushi.lenovo.asia5b.app_di.other.presenter.MainActivityPresenter;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_event.MainTabEvent;
import com.wushi.lenovo.asia5b.app_event.NonetEvent;
import com.wushi.lenovo.asia5b.app_event.OrderItemEvent;
import com.wushi.lenovo.asia5b.app_event.OrderPayEvent;
import com.wushi.lenovo.asia5b.app_event.PostPackEvent;
import com.wushi.lenovo.asia5b.app_event.ReadNotificationEvent;
import com.wushi.lenovo.asia5b.app_model.other.CategoryModel;
import com.wushi.lenovo.asia5b.app_model.other.MainTabType;
import com.wushi.lenovo.asia5b.app_push.FireBasePushHelper;
import com.wushi.lenovo.asia5b.app_push.MyFirebaseMessagingService;
import com.wushi.lenovo.asia5b.app_push.PushHelper;
import com.wushi.lenovo.asia5b.app_ui.good.activity.ThirdMallActivity;
import com.wushi.lenovo.asia5b.app_ui.good.fragment.OrderFragment;
import com.wushi.lenovo.asia5b.app_ui.h5.CategoryActivity;
import com.wushi.lenovo.asia5b.app_ui.home.fragment.HomeFragment;
import com.wushi.lenovo.asia5b.app_ui.login.activity.LoginThridActivity;
import com.wushi.lenovo.asia5b.app_ui.other.adapter.MainMenuAdapter;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.NoNetDialog;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.SetLanguageDialogFragment;
import com.wushi.lenovo.asia5b.app_ui.profile.fragment.MineFragment;
import com.wushi.lenovo.asia5b.app_ui.wish.fragment.WishFragment;
import com.wushi.lenovo.asia5b.app_utils.ConnectUtils;
import com.wushi.lenovo.asia5b.app_utils.helper.UriHelper;
import com.wushi.lenovo.asia5b.app_widget.bottomtab.WAlphaTabsIndicator;
import com.wushi.lenovo.asia5b.debug.DebugType;
import com.wushi.lenovo.asia5b.debug.activity.DebugActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2018/9/10.
 * App主页
 */
public class MainActivity extends BaseMvpActivity<
        MainActivityView, MainActivityPresenter> implements MainActivityView {

    @BindView(R.id.home_view_pager)
    ViewPager viewPager;
    @BindView(R.id.rv_main)
    RecyclerView mRecyclerView;
    @BindView(R.id.drawerlayout)
    public DrawerLayout drawerlayout;
    @BindView(R.id.statusview)
    public View statusview;
    @BindView(R.id.ll_home_vessel)
    LinearLayout ll_home_vessel;
    @BindView(R.id.tv_main_versioncode)
    TextView tv_main_versioncode;
    @BindView(R.id.tab_main_bottom)
    WAlphaTabsIndicator wAlphaTabsIndicator;

    private MainMenuAdapter menuAdapter;
    private OrderFragment orderFragment;


    @Override
    public void checkTabItem(int index) {
        if (index == 0 || index == 2) {
            drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        } else {
            drawerlayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        }
        if (index == 4) {
            statusview.setVisibility(View.GONE);
        } else {
            statusview.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        setStatusTrans();
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

        //路由分离
        router(getIntent());
        //选择语言
        showSetLanguageDialog();
        /**
         * isStartLogin true 需要跳转登录页面
         */
        boolean isStartLogin = getIntent().getBooleanExtra("isStartLogin", false);
        if (isStartLogin && !UserRepository.isLogin()) {
            startActivity(new Intent(this, LoginThridActivity.class));
        }

        initViewPager();
        initView();
        initData();
        initEvent();
        resetView();

        //监听剪切板
        getPresenter().registClip(this);

        MalayAsiaApplication.finishActivity(SplashActivity.class);
        MalayAsiaApplication.finishActivity(LoginThridActivity.class);
        nonet();
        new RxPermissions(mActivity)
                .request(Manifest.permission.CHANGE_NETWORK_STATE)//为了兼容安卓6.0,因为安卓6.0中默认对该权限关闭了
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

                        connectivityManager.requestNetwork(new NetworkRequest.Builder().build(),
                                new ConnectivityManager.NetworkCallback() {
                                    @Override
                                    public void onAvailable(Network network) {
                                        super.onAvailable(network);
                                        ConnectUtils.INSTANCE.isMobileEnable(mActivity);
                                        EventBus.getDefault().post(new NonetEvent());
//                        nonet();
                                    }

                                    @Override
                                    public void onUnavailable() {
                                        super.onUnavailable();
                                    }

                                    @Override
                                    public void onLost(Network network) {
                                        super.onLost(network);
                                        nonet();
                                    }
                                });
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });


    }


    private void nonet() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!ConnectUtils.INSTANCE.isConnect(mActivity)
                        && !ConnectUtils.INSTANCE.isWifiEnable(mActivity)
                        && !ConnectUtils.INSTANCE.isMobileEnable(mActivity)
                ) {
                    Activity endActivity = MalayAsiaApplication.getEndActivity();
                    if (endActivity == null) {
                        return;
                    }
                    NoNetDialog noNetDialog = new NoNetDialog(endActivity);
                    noNetDialog.show();
                }
            }
        });

    }

    /**
     * 重置页面,从facebook/google等第三方APP跳转本App后,经过SplashActivity转手到这里进行路由分离
     * asia5bnew.com://asia5bnew.com/login/resetpassword?memberid=1&validcode=123456
     * schme://host/登录模块/重置密码页面?会员id&验证code
     *
     * @param dataIntent
     */
    protected void router(Intent dataIntent) {
        if (dataIntent != null && dataIntent.getData() != null) {
            UriHelper.parseUri(dataIntent.getData(), this);
        }
    }

    /**
     * 选择语言,如果没设置过语言,就显示该dialog
     */
    private void showSetLanguageDialog() {
        if (GlobalValue.isFirstSetLanguage()) {
            //保存设置过语言
            GlobalValue.saveFirstSetLanguage(false);
            SetLanguageDialogFragment setLanguageDialogFragment = new SetLanguageDialogFragment();
            setLanguageDialogFragment.show(getSupportFragmentManager(), "SetLanguageDialogFragment");
        }


    }

    /**
     * 再次启动
     *
     * @param intent
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        router(intent);
        //解析来自firebase推送的数据
        if (intent.getIntExtra(FireBasePushHelper.channel_data, 0) == FireBasePushHelper.channel_data_value) {
            PushHelper.channelData(MyFirebaseMessagingService.bean);
        }
    }

    /**
     * 初始化视图
     */
    @Override
    protected void initView() {
        //设置版本
        tv_main_versioncode.setText("Version " + getPresenter().getVersion(this) + (BuildConfig.appType == 0 ? ".test" : ""));
        wAlphaTabsIndicator.setViewPager(viewPager);

        //设置左变菜单列表
        List<CategoryModel> firstCategorys = getPresenter().getFirstCategorys();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        menuAdapter = new MainMenuAdapter(firstCategorys);
        menuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CategoryModel item = (CategoryModel) adapter.getItem(position);
                CategoryActivity.startCategoryActivity(mActivity, item);
                drawerlayout.closeDrawer(Gravity.LEFT);
            }
        });
        /**
         * 增加测试的几个按钮
         */
        if (GlobalValue.isDebug && true && BuildConfig.appType == 0) {
            View debugView = View.inflate(this, R.layout.view_main_debug, null);
            TextView tv_main_test1 = debugView.findViewById(R.id.tv_main_test1);
            tv_main_test1.setOnClickListener(v -> {
                startActivity(new Intent(this, ThirdMallActivity.class));
            });
            TextView tv_main_test2 = debugView.findViewById(R.id.tv_main_test2);
            tv_main_test2.setOnClickListener(v -> {
            });
            TextView tv_main_versionmanager = debugView.findViewById(R.id.tv_main_versionmanager);
            tv_main_versionmanager.setOnClickListener(v -> {
                Intent intent = new Intent(this, DebugActivity.class);
                intent.putExtra("type", DebugType.VERSIONMANAGER);
                startActivity(intent);
            });
            TextView tv_main_versionh5 = debugView.findViewById(R.id.tv_main_versionh5);
            tv_main_versionh5.setOnClickListener(v -> {
                Intent intent = new Intent(this, DebugActivity.class);
                intent.putExtra("type", DebugType.VERSIONH5);
                startActivity(intent);
            });
            TextView tv_main_goodsid = debugView.findViewById(R.id.tv_main_goodsid);
            tv_main_goodsid.setOnClickListener(v -> {
                Intent intent = new Intent(this, DebugActivity.class);
                intent.putExtra("type", DebugType.GOODS_ID);
                startActivity(intent);
            });
            TextView tv_main_debugh5 = debugView.findViewById(R.id.tv_main_debugh5);
            tv_main_debugh5.setOnClickListener(v -> {
                Intent intent = new Intent(this, DebugActivity.class);
                intent.putExtra("type", DebugType.DEBUGH5);
                startActivity(intent);
            });
            TextView tv_main_push = debugView.findViewById(R.id.tv_main_push);
            tv_main_push.setOnClickListener(v -> {
                Intent intent = new Intent(this, DebugActivity.class);
                intent.putExtra("type", DebugType.PUSH);
                startActivity(intent);
            });
            menuAdapter.addFooterView(debugView);
        }
        mRecyclerView.setAdapter(menuAdapter);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(MainActivity.this, DividerItemDecoration.VERTICAL));


    }


    /**
     * 初始化viewpager
     */
    private void initViewPager() {
        List<Fragment> fragmentList = new ArrayList<>();//fragment的集合
        //首页
        HomeFragment homeFragment = (HomeFragment) HomeFragment.sNewStance(this, HomeFragment.class);
        fragmentList.add(homeFragment);
        //收藏
        fragmentList.add(WishFragment.sNewStance(this, WishFragment.class));
        //购物车
//        fragmentList.add(ShopCarFragment.sNewStance(this, ShopCarFragment.class));
        Bundle bundle = new Bundle();
        bundle.putBoolean("isPiFragment", true);
        Fragment piFragment = HomeFragment.sNewStance(this, HomeFragment.class, bundle);
        fragmentList.add(piFragment);
        //订单
        orderFragment = (OrderFragment) OrderFragment.sNewStance(this, OrderFragment.class);
        fragmentList.add(orderFragment);
        //个人
        MineFragment mineFragment = (MineFragment) MineFragment.sNewStance(this, MineFragment.class);
        fragmentList.add(mineFragment);

        BaseFragmentPagerAdapter fragmentAdapter = new BaseFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(fragmentAdapter);
        viewPager.setOffscreenPageLimit(5);
    }


    /**
     * 重置整个视图
     */
    private void resetView() {
        setTabCurrenItem(0);
        //清除缓存
        WishRepository.setWishCount(0);
        ShopRepository.setShopCount(0);
        OrderRepository.setOrderCount(0);
        InboxRepository.setInboxCount(0);
    }

    /**
     * 切换tab
     *
     * @param index 角标
     */
    public void setTabCurrenItem(@IntRange(from = 0, to = 4) int index) {
        wAlphaTabsIndicator.setTabCurrenItem(index);

    }

    /**
     * 设置右上角提醒数字
     *
     * @param type tab 类型
     */
    public void setNumber(MainTabType type) {
        wAlphaTabsIndicator.setNumber(type);
    }

    /**
     * 初始化事件
     */
    @Override
    protected void initEvent() {
        initDrawerListener();
        tv_main_versioncode.setOnClickListener(v -> {
            getPresenter().checkUpdate(mActivity, true);
        });
        //订阅购物车数量
        Disposable shopSubject = ShopRepository.getShopCountOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(integer -> {
                    setNumber(MainTabType.shop);
                });
        composite.add(shopSubject);
        //订阅订单数量
        Disposable orderSubject = OrderRepository.getOrderCountOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(integer -> {
                    setNumber(MainTabType.order);
                });
        composite.add(orderSubject);
        //订阅订单数量
        Disposable wishSubject = WishRepository.getWishCountOB()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(integer -> {
                    setNumber(MainTabType.wish);
                });
        composite.add(wishSubject);
    }


    /**
     * 抽屉效果的监听
     */
    public void initDrawerListener() {


        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawerlayout, null, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                /**
                 * 整个页面左右移动
                 */
                ll_home_vessel.setTranslationX(drawerView.getMeasuredWidth() * slideOffset);
                ll_home_vessel.invalidate();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                /**
                 * 每次打开菜单,检测菜单数据是否存在
                 */
                List<CategoryModel> categoryModels = menuAdapter.getData();
                if (categoryModels == null || categoryModels.size() == 1) {
                    getPresenter().getFirstCategorys();
                }
            }
        };
        toggle.syncState();
        drawerlayout.addDrawerListener(toggle);
    }

    /**
     * 抽屉效果的打开
     */
    public void openDrawerlayout() {
        drawerlayout.openDrawer(Gravity.LEFT);
    }


    /**
     * 初始化加载数据
     */
    @Override
    protected void initData() {
        if (UserRepository.isLogin()) {
            //更新用户资料
            UserRepository.updateUserInfo();
            getWishCount();
            OrderRepository.updateOrderCount();
            ShopRepository.updateShopCount();
        }
        //延迟加载数据
        getPresenter().delayData(mActivity);
        //显示广告
//        AdvDialog.showAdvDialog(this);//由H5显示


    }

    /**
     * 获取收藏数量
     */
    public void getWishCount() {
        WishRepository.updateWishCount();
    }

    /**
     * 获取左边菜单列表的回调
     *
     * @param categoryModels
     */
    public void getFirstCategorysResult(List<CategoryModel> categoryModels) {
        if (categoryModels != null) {
            menuAdapter.setNewData(categoryModels);
        }
    }

    /**
     * 点击返回按钮时
     */
    @Override
    public void onBackPressed() {
        if (drawerlayout.isDrawerOpen(Gravity.LEFT)) {
            drawerlayout.closeDrawer(Gravity.LEFT);
        } else {
            //按返回键返回桌面
            moveTaskToBack(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onLoginEvent(LoginEvent event) {
        //登录状态有改变
        if (event != null) {

            if (TextUtils.equals(event.loginState, CommonConstant.LOGIN_SUCCESS)) {
                d("--->>>>>>>>---登录成功");
                Observable.intervalRange(0, 7, 0, 100, TimeUnit.MILLISECONDS)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> {
                            //todo aLong表示次数
                            if (aLong == 0) {
                                ShopRepository.updateShopCount();
                            } else if (aLong == 1) {
                                OrderRepository.updateOrderCount();
                            } else if (aLong == 2) {
                                getWishCount();
                            } else if (aLong == 3) {
                                getPresenter().getCreditMin();
                            } else if (aLong == 4) {
                                MemberBlanceRepository.updateMemberBalance();
                            } else if (aLong == 5) {
                                //重新更新推送资料
                                PushHelper.updateDeviceToken();
                            } else if (aLong == 6) {

                            }
                        }, throwable -> {
                        });
                setTabCurrenItem(0);


            } else if (TextUtils.equals(event.loginState, CommonConstant.LOGOUT_SUCCESS)) {
                d("--->>>>>>>>---退出登录");
                resetView();
                MemberBlanceRepository.setMemberBalance(null);
            }
        }


    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onMainTabEvent(MainTabEvent event) {
        if (event != null) {
            if (event.index >= 0 && event.index <= 4) {
                if (event.index == 3) {
                    orderFragment.setCurrentPosition(event.currentPosition);
                }
                setTabCurrenItem(event.index);
                //如果是订单另行设置
                if (event.index == 3) {
                    EventBus.getDefault().post(new OrderItemEvent(event.currentPosition));
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onReadNotificationEvent(ReadNotificationEvent event) {
        if (event != null) {
            getPresenter().readNotifacation(event.notification_id, event.notification_type);
        }
    }

    /**
     * 申请打包
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onPostPackEvent(PostPackEvent event) {
        setTabCurrenItem(3);
    }


    /**
     * 订单付款成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onOrderPayEvent(OrderPayEvent event) {
        if (event != null && event.resultModel.isSuccess()) {
            setTabCurrenItem(3);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onTaokouEvent(TaokouEvent event) {
        if (event != null && !TextUtils.isEmpty(event.url)) {
            getPresenter().getProductByKouling(event.url);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        wAlphaTabsIndicator.checkItem();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


}
